<?php

namespace App\Http\Controllers\Firm;

use App\Events\Like;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LikeController extends BaseController
{


    public function store(Request $request)
    {
        $param = $this->validate($request,[
            'firm_id' => 'required|integer'
        ]);
        $user_id = auth('api')->id();
        $status = DB::table('user_like_firms')
            ->where([
                'user_id' => $user_id,
                'firm_id' => $param['firm_id']
            ])->value('status');

        if (empty($status) || $status==1){
            event(new Like($user_id));
        }


        if (empty($status)){
            $result =  DB::table('user_like_firms')->insert([
                'user_id' => $user_id,
                'firm_id' => $param['firm_id'],
                'status' => 1,
                'like_time' => date('Y-m-d H:i:s')
            ]);
            return $result ? $this->success() :$this->error();
        }

        $status = $status==1 ? 2 : 1;
        $result = DB::table('user_like_firms')->where([
            'user_id' => $user_id,
            'firm_id' => $param['firm_id'],
        ])->update([
            'status' => $status,
            'like_time' => date('Y-m-d H:i:s')
        ]);



        return $result ? $this->success() :$this->error();

    }
}
